package com.rowger.player.ui.fragment

import android.graphics.Color
import android.support.v7.widget.LinearLayoutManager
import android.view.Gravity
import android.view.View
import android.widget.TextView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.itheima.player.model.bean.HomeItemBean
import com.rowger.player.R
import com.rowger.player.adapter.HomeAdapter
import com.rowger.player.base.BaseFragment
import com.rowger.player.util.ThreadUtil
import com.rowger.player.util.URLProviderUtils
import kotlinx.android.synthetic.main.fragment_home.*
import okhttp3.*
import java.io.File
import java.io.IOException
import javax.xml.transform.Templates

/**
 * Created by Administrator on 2018/5/10.
 */
class HomeFragment : BaseFragment() {
    val adapter by lazy { HomeAdapter() }
    override fun initView(): View? {
     return View.inflate(context, R.layout.fragment_home,null)
    }

    override fun initLisener(){
        recycleView.layoutManager=LinearLayoutManager(context)

        recycleView.adapter=adapter
    }
    override fun initData(){
        loadDatas()
    }

    private fun loadDatas() {
      val path=URLProviderUtils.getHomeUrl(0,20)
      val client = OkHttpClient()
      val request = Request.Builder()
              .url(path)
              .get()
              .build()

       client.newCall(request).enqueue(object :Callback{
           /*
           * 子线程调用
           * */
           override fun onFailure(call: Call?, e: IOException?) {
              println("获取数据出错:"+Thread.currentThread().name)
               myToast("获取数据出错")
           }
           /*
          * 子线程调用
          * */
           override fun onResponse(call: Call?, response: Response?) {
               myToast("获取数据成功")
               val  result=response?.body()?.string()
               val gson=Gson()
               val list = gson.fromJson<List<HomeItemBean>>(result,object :TypeToken<List<HomeItemBean>>(){}.type)
               println("获取数据成功:"+result)
               //刷新列表
               ThreadUtil.runOnMainThread(object :Runnable{
                   override fun run() {
                       adapter.updateList(list)
                   }
               })
           }
       })
    }
}